/**
 * 主应用程序 - 负责模块切换、数据加载和用户交互
 */

class SupplyChainApp {
    constructor() {
        this.currentModule = 'dashboard';
        this.isLoading = false;
        this.refreshInterval = null;
        this.refreshIntervalTime = 30000; // 30秒
        
        this.init();
    }
    
    /**
     * 初始化应用
     */
    async init() {
        this.setupEventListeners();
        
        // 测试API连接
        await this.testAPIConnection();
        
        // 加载默认模块
        await this.loadModule(this.currentModule);
    }
    
    /**
     * 设置事件监听器
     */
    setupEventListeners() {
        // 导航菜单点击事件
        document.querySelectorAll('.nav-link').forEach(link => {
            link.addEventListener('click', (e) => {
                e.preventDefault();
                const module = e.target.dataset.module;
                if (module) {
                    this.loadModule(module);
                }
            });
        });
        
        // 刷新按钮点击事件
        const refreshBtn = document.getElementById('refreshBtn');
        if (refreshBtn) {
            refreshBtn.addEventListener('click', () => {
                this.refreshCurrentModule();
            });
        }
        
        // 模态框关闭事件
        const modal = document.getElementById('detailModal');
        if (modal) {
            modal.addEventListener('click', (e) => {
                if (e.target === modal || e.target.classList.contains('close')) {
                    this.closeModal();
                }
            });
        }
        
        // ESC键关闭模态框
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                this.closeModal();
            }
        });
        
        // 自动刷新开关
        const autoRefreshToggle = document.getElementById('autoRefreshToggle');
        if (autoRefreshToggle) {
            autoRefreshToggle.addEventListener('change', (e) => {
                this.toggleAutoRefresh(e.target.checked);
            });
        }
    }
    
    /**
     * 测试API连接
     */
    async testAPIConnection() {
        try {
            await window.apiClient.testConnection();
        } catch (error) {
            console.error('API连接测试失败:', error);
        }
    }
    
    /**
     * 加载模块
     */
    async loadModule(moduleName) {
        if (this.isLoading) return;
        
        this.isLoading = true;
        this.currentModule = moduleName;
        
        // 更新导航状态
        this.updateNavigation(moduleName);
        
        // 显示对应的模块内容
        this.showModuleContent(moduleName);
        
        // 加载模块数据
        await this.loadModuleData(moduleName);
        
        this.isLoading = false;
    }
    
    /**
     * 导航到指定模块（用于KPI卡片点击）
     */
    navigateToModule(moduleName) {
        this.loadModule(moduleName);
    }
    
    /**
     * 更新导航状态
     */
    updateNavigation(activeModule) {
        document.querySelectorAll('.nav-link').forEach(link => {
            link.classList.remove('active');
            if (link.dataset.module === activeModule) {
                link.classList.add('active');
            }
        });
    }
    
    /**
     * 显示模块内容
     */
    showModuleContent(moduleName) {
        // 隐藏所有模块
        document.querySelectorAll('.module-content').forEach(module => {
            module.style.display = 'none';
        });
        
        // 显示当前模块
        const currentModuleElement = document.getElementById(`${moduleName}-content`);
        if (currentModuleElement) {
            currentModuleElement.style.display = 'block';
        } else {
            console.warn(`模块 ${moduleName}-content 不存在`);
        }
    }
    
    /**
     * 加载模块数据
     */
    async loadModuleData(moduleName) {
        try {
            switch (moduleName) {
                case 'dashboard':
                    await this.loadDashboardData();
                    break;
                case 'inventory':
                    await this.loadInventoryData();
                    break;
                case 'orders':
                    await this.loadOrdersData();
                    break;
                case 'analytics':
                    await this.loadAnalyticsData();
                    break;
                case 'planning':
                    // 初始化计划管理模块
                    initPlanningModule();
                    break;
                case 'sourcing':
                    await this.loadSourcingData();
                    break;
                case 'manufacturing':
                    await this.loadManufacturingData();
                    break;
                case 'delivery':
                    await this.loadDeliveryData();
                    break;
                case 'quality':
                    await this.loadQualityData();
                    break;
                default:
                    console.warn(`未知模块: ${moduleName}`);
            }
        } catch (error) {
            console.error(`加载${moduleName}模块数据失败:`, error);
            this.showError(`加载${moduleName}模块数据失败`);
        }
    }
    
    /**
     * 加载仪表板数据
     */
    async loadDashboardData() {
        try {
            // 加载KPI数据
            const kpiData = await window.apiClient.getDashboardKPIs();
            this.updateKPICards(kpiData);
            
            // 加载图表数据
            const inventoryChartData = await window.apiClient.getInventoryChartData();
            window.chartManager.createInventoryChart('inventoryChart', inventoryChartData);
            
            const orderChartData = await window.apiClient.getOrderTrendChartData();
            window.chartManager.createOrderTrendChart('orderChart', orderChartData);
            
            // 加载采购数据图表
            const procurementData = await window.apiClient.getProcurementChartData();
            window.chartManager.createProcurementChart('procurementChart', procurementData);
            
            // 加载生产数据图表
            const productionData = await window.apiClient.getProductionChartData();
            window.chartManager.createProductionChart('productionChart', productionData);
            
            // 加载配送数据图表
            const deliveryData = await window.apiClient.getDeliveryChartData();
            window.chartManager.createDeliveryChart('deliveryChart', deliveryData);
            
            // 加载质量数据图表
            const qualityData = await window.apiClient.getQualityChartData();
            window.chartManager.createQualityChart('qualityChart', qualityData);
            
            // 加载业务活动数据
            const activitiesData = await window.apiClient.getBusinessActivities();
            this.updateActivitiesTable(activitiesData);
            
        } catch (error) {
            console.error('加载仪表板数据失败:', error);
        }
    }
    
    /**
     * 加载库存数据
     */
    async loadInventoryData() {
        try {
            // 加载库存统计
            const stats = await window.apiClient.getInventoryStats();
            this.updateInventoryStats(stats);
            
            // 加载库存列表
            const inventory = await window.apiClient.getInventoryData();
            this.updateInventoryTable(inventory);
            
            // 加载仓库列表
            const warehouses = await window.apiClient.getWarehouses();
            this.updateWarehouseSelect(warehouses);
            
            // 加载产品类别
            const categories = await window.apiClient.getProductCategories();
            this.updateCategorySelect(categories);
            
        } catch (error) {
            console.error('加载库存数据失败:', error);
        }
    }
    
    /**
     * 加载订单数据
     */
    async loadOrdersData() {
        try {
            // 加载订单统计
            const stats = await window.apiClient.getOrdersStats();
            this.updateOrdersStats(stats);
            
            // 加载订单列表
            const orders = await window.apiClient.getOrdersData();
            this.updateOrdersTable(orders);
            
        } catch (error) {
            console.error('加载订单数据失败:', error);
        }
    }
    
    /**
     * 加载智能分析数据
     */
    async loadAnalyticsData() {
        try {
            // 默认加载需求预测
            await this.loadForecastData();
            
            // 设置分析标签页事件
            this.setupAnalyticsTabs();
            
        } catch (error) {
            console.error('加载智能分析数据失败:', error);
        }
    }
    
    /**
     * 加载采购管理数据
     */
    async loadSourcingData() {
        try {
            // 加载采购统计
            const stats = await window.apiClient.getProcurementStats();
            this.updateProcurementStats(stats);
            
            // 加载供应商数据
            const suppliers = await window.apiClient.getSuppliers();
            this.updateSupplierTable(suppliers);
            
            // 加载采购图表
            const chartData = await window.apiClient.getProcurementChartData();
            this.updateProcurementCharts(chartData);
            
        } catch (error) {
            console.error('加载采购数据失败:', error);
        }
    }
    
    /**
     * 加载生产管理数据
     */
    async loadManufacturingData() {
        try {
            // 加载生产统计
            const stats = await window.apiClient.getProductionStats();
            this.updateProductionStats(stats);
            
            // 加载生产订单
            const orders = await window.apiClient.getProductionOrders();
            this.updateProductionOrders(orders);
            
            // 加载生产图表
            const chartData = await window.apiClient.getProductionChartData();
            this.updateProductionCharts(chartData);
            
        } catch (error) {
            console.error('加载生产数据失败:', error);
        }
    }
    
    /**
     * 加载配送管理数据
     */
    async loadDeliveryData() {
        try {
            // 加载配送统计
            const stats = await window.apiClient.getDeliveryStats();
            this.updateDeliveryStats(stats);
            
            // 加载物流状态
            const logistics = await window.apiClient.getLogisticsStatus();
            this.updateLogisticsStatus(logistics);
            
            // 加载配送图表
            const chartData = await window.apiClient.getDeliveryChartData();
            this.updateDeliveryCharts(chartData);
            
        } catch (error) {
            console.error('加载配送数据失败:', error);
        }
    }
    
    /**
     * 加载质量管理数据
     */
    async loadQualityData() {
        try {
            // 加载质量统计
            const stats = await window.apiClient.getQualityStats();
            this.updateQualityStats(stats);
            
            // 加载质量检查记录
            const inspections = await window.apiClient.getQualityInspections();
            this.updateInspectionTable(inspections);
            
            // 加载质量图表
            const chartData = await window.apiClient.getQualityChartData();
            this.updateQualityCharts(chartData);
            
        } catch (error) {
            console.error('加载质量数据失败:', error);
        }
    }
    
    /**
     * 更新KPI卡片
     */
    updateKPICards(data) {
        if (!data) return;
        
        // 更新库存周转率
        const inventoryTurnover = document.getElementById('inventoryTurnover');
        if (inventoryTurnover) {
            inventoryTurnover.textContent = data.inventoryTurnover || '0';
        }
        
        // 更新订单完成率
        const orderFulfillment = document.getElementById('orderFulfillment');
        if (orderFulfillment) {
            orderFulfillment.textContent = `${data.orderFulfillment || 0}%`;
        }
        
        // 更新供应商准时率
        const supplierOnTime = document.getElementById('supplierOnTime');
        if (supplierOnTime) {
            supplierOnTime.textContent = `${data.supplierOnTime || 0}%`;
        }
        
        // 更新成本节约
        const costSavings = document.getElementById('costSavings');
        if (costSavings) {
            costSavings.textContent = `¥${data.costSavings || 0}`;
        }
    }
    
    /**
     * 更新业务活动表格
     */
    updateActivitiesTable(data) {
        const tbody = document.querySelector('#activitiesTable tbody');
        if (!tbody || !data || !data.activities) return;
        
        tbody.innerHTML = data.activities.map(activity => `
            <tr>
                <td>${activity.time}</td>
                <td>${activity.type}</td>
                <td>${activity.description}</td>
                <td><span class="status-badge status-${activity.status}">${activity.statusText}</span></td>
            </tr>
        `).join('');
    }
    
    /**
     * 更新库存统计
     */
    updateInventoryStats(data) {
        if (!data) return;
        
        const statsContainer = document.querySelector('#inventory-stats');
        if (statsContainer) {
            statsContainer.innerHTML = `
                <div class="stat-item">
                    <div class="stat-value">${data.totalItems || 0}</div>
                    <div class="stat-label">总商品数</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${data.lowStock || 0}</div>
                    <div class="stat-label">低库存</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${data.outOfStock || 0}</div>
                    <div class="stat-label">缺货商品</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${data.totalValue || 0}</div>
                    <div class="stat-label">库存总值</div>
                </div>
            `;
        }
    }
    
    /**
     * 更新库存表格
     */
    updateInventoryTable(data) {
        const tbody = document.querySelector('#inventoryTable tbody');
        if (!tbody || !data || !data.items) return;
        
        tbody.innerHTML = data.items.map(item => `
            <tr onclick="app.showItemDetail('${item.id}')" style="cursor: pointer;">
                <td>${item.sku}</td>
                <td>${item.name}</td>
                <td>${item.category}</td>
                <td>${item.quantity}</td>
                <td>${item.unit}</td>
                <td><span class="status-badge status-${item.status}">${item.statusText}</span></td>
                <td>${item.warehouse}</td>
                <td>¥${item.unitPrice}</td>
            </tr>
        `).join('');
    }
    
    /**
     * 更新订单统计
     */
    updateOrdersStats(data) {
        if (!data) return;
        
        const statsContainer = document.querySelector('#orders-stats');
        if (statsContainer) {
            statsContainer.innerHTML = `
                <div class="stat-item">
                    <div class="stat-value">${data.totalOrders || 0}</div>
                    <div class="stat-label">总订单数</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${data.pendingOrders || 0}</div>
                    <div class="stat-label">待处理</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${data.completedOrders || 0}</div>
                    <div class="stat-label">已完成</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">¥${data.totalAmount || 0}</div>
                    <div class="stat-label">总金额</div>
                </div>
            `;
        }
    }
    
    /**
     * 更新订单表格
     */
    updateOrdersTable(data) {
        const tbody = document.querySelector('#ordersTable tbody');
        if (!tbody || !data || !data.orders) return;
        
        tbody.innerHTML = data.orders.map(order => {
            let statusClass = 'info';
            let statusText = order.status;
            
            if (order.status === '已完成') statusClass = 'success';
            else if (order.status === '已取消') statusClass = 'danger';
            else if (order.status === '处理中') statusClass = 'warning';
            
            return `
                <tr onclick="app.showOrderDetail('${order.order_id}')" style="cursor: pointer;">
                    <td>${order.order_id}</td>
                    <td>${order.customer_name}</td>
                    <td>¥${order.total_amount}</td>
                    <td><span class="status-badge status-${statusClass}">${statusText}</span></td>
                    <td>${order.order_date}</td>
                    <td>${order.delivery_date || '未确定'}</td>
                </tr>
            `;
        }).join('');
    }
    
    /**
     * 设置分析标签页
     */
    setupAnalyticsTabs() {
        const tabButtons = document.querySelectorAll('#analytics-content .tab-button');
        const tabContents = document.querySelectorAll('#analytics-content .tab-content');
        
        tabButtons.forEach(button => {
            button.addEventListener('click', async () => {
                const tabType = button.dataset.tab;
                
                // 更新按钮状态
                tabButtons.forEach(btn => btn.classList.remove('active'));
                button.classList.add('active');
                
                // 更新内容显示
                tabContents.forEach(content => content.classList.remove('active'));
                const targetContent = document.getElementById(`${tabType}-tab`);
                if (targetContent) {
                    targetContent.classList.add('active');
                }
                
                // 加载对应数据
                await this.loadAnalyticsTab(tabType);
            });
        });
    }
    
    /**
     * 加载分析标签页数据
     */
    async loadAnalyticsTab(tabType) {
        try {
            switch (tabType) {
                case 'forecast':
                    await this.loadForecastData();
                    break;
                case 'optimization':
                    await this.loadOptimizationData();
                    break;
                case 'supplier':
                    await this.loadSupplierData();
                    break;
                case 'trends':
                    await this.loadTrendsData();
                    break;
            }
        } catch (error) {
            console.error(`加载${tabType}数据失败:`, error);
        }
    }
    
    /**
     * 加载需求预测数据
     */
    async loadForecastData() {
        const data = await window.apiClient.getDemandForecast();
        
        // 更新预测图表
        if (window.chartManager && data) {
            window.chartManager.createForecastChart('forecastChart', data);
        }
        
        // 更新预测表格
        this.updateForecastTable(data);
    }
    
    /**
     * 加载优化建议数据
     */
    async loadOptimizationData() {
        const data = await window.apiClient.getOptimizationSuggestions();
        this.updateOptimizationTable(data);
    }
    
    /**
     * 更新预测表格
     */
    updateForecastTable(data) {
        const tbody = document.querySelector('#forecastTable tbody');
        if (!tbody || !data || !data.forecasts) return;
        
        tbody.innerHTML = data.forecasts.map(forecast => `
            <tr>
                <td>${forecast.product}</td>
                <td>${forecast.currentDemand}</td>
                <td>${forecast.predictedDemand}</td>
                <td>${forecast.confidence}%</td>
                <td>${forecast.trend}</td>
            </tr>
        `).join('');
    }
    
    /**
     * 更新优化建议表格
     */
    updateOptimizationTable(data) {
        const tbody = document.querySelector('#optimizationTable tbody');
        if (!tbody || !data || !data.suggestions) return;
        
        tbody.innerHTML = data.suggestions.map(suggestion => `
            <tr>
                <td>${suggestion.type}</td>
                <td>${suggestion.description}</td>
                <td>${suggestion.impact}</td>
                <td><span class="priority-badge priority-${suggestion.priority}">${suggestion.priorityText}</span></td>
            </tr>
        `).join('');
    }
    
    /**
     * 更新采购统计
     */
    updateProcurementStats(data) {
        if (!data) return;
        
        const statsContainer = document.querySelector('#procurement-stats');
        if (statsContainer) {
            statsContainer.innerHTML = `
                <div class="stat-item">
                    <div class="stat-value">${data.totalSuppliers || 0}</div>
                    <div class="stat-label">供应商数量</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${data.activeContracts || 0}</div>
                    <div class="stat-label">活跃合同</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${data.onTimeDelivery || 0}%</div>
                    <div class="stat-label">准时交付率</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">¥${data.totalSpend || 0}</div>
                    <div class="stat-label">总采购额</div>
                </div>
            `;
        }
    }
    
    /**
     * 更新供应商表格
     */
    updateSupplierTable(data) {
        const tbody = document.querySelector('#supplierTable tbody');
        if (!tbody || !data || !data.suppliers) return;
        
        tbody.innerHTML = data.suppliers.map(supplier => {
            // 确定状态
            let status = 'active';
            let statusText = '活跃';
            if (supplier.credit_rating < 3) {
                status = 'warning';
                statusText = '关注';
            } else if (supplier.credit_rating < 2) {
                status = 'danger';
                statusText = '风险';
            }
            
            return `
                <tr onclick="app.showSupplierDetail('${supplier.id}')" style="cursor: pointer;">
                    <td>${supplier.name}</td>
                    <td>${supplier.category}</td>
                    <td>${supplier.credit_rating}/5</td>
                    <td>${supplier.on_time_rate}%</td>
                    <td><span class="status-badge status-${status}">${statusText}</span></td>
                    <td>${supplier.contact}</td>
                </tr>
            `;
        }).join('');
    }
    
    /**
     * 更新采购图表
     */
    updateProcurementCharts(data) {
        if (!data || !window.chartManager) return;
        
        // 更新采购趋势图表
        if (data.trendData) {
            window.chartManager.createProcurementTrendChart('procurementTrendChart', data.trendData);
        }
        
        // 更新供应商性能图表
        if (data.performanceData) {
            window.chartManager.createSupplierPerformanceChart('supplierPerformanceChart', data.performanceData);
        }
        
        // 显示采购统计
        const statsContainer = document.querySelector('#procurement-chart-stats');
        if (statsContainer && data.stats) {
            statsContainer.innerHTML = `
                <div class="chart-stat">
                    <span class="stat-label">本月采购额:</span>
                    <span class="stat-value">¥${data.stats.monthlySpend || 0}</span>
                </div>
                <div class="chart-stat">
                    <span class="stat-label">平均交付时间:</span>
                    <span class="stat-value">${data.stats.avgDeliveryTime || 0}天</span>
                </div>
                <div class="chart-stat">
                    <span class="stat-label">质量合格率:</span>
                    <span class="stat-value">${data.stats.qualityRate || 0}%</span>
                </div>
            `;
        }
    }
    
    /**
     * 更新生产统计
     */
    updateProductionStats(data) {
        if (!data) return;
        
        const statsContainer = document.querySelector('#production-stats');
        if (statsContainer) {
            statsContainer.innerHTML = `
                <div class="stat-item">
                    <div class="stat-value">${data.totalOrders || 0}</div>
                    <div class="stat-label">生产订单</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${data.efficiency || 0}%</div>
                    <div class="stat-label">生产效率</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${data.qualityRate || 0}%</div>
                    <div class="stat-label">质量合格率</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${data.capacity || 0}%</div>
                    <div class="stat-label">产能利用率</div>
                </div>
            `;
        }
    }
    
    /**
     * 更新生产订单表格
     */
    updateProductionOrders(data) {
        const tbody = document.querySelector('#productionOrdersTable tbody');
        if (!tbody || !data || !data.orders) return;
        
        tbody.innerHTML = data.orders.map(order => {
            let statusClass = 'info';
            let statusText = order.status;
            
            if (order.status === '已完成') statusClass = 'success';
            else if (order.status === '已取消') statusClass = 'danger';
            else if (order.status === '生产中') statusClass = 'warning';
            else if (order.status === '待开始') statusClass = 'info';
            
            return `
                <tr onclick="app.showProductionOrderDetail('${order.id}')" style="cursor: pointer;">
                    <td>${order.order_id}</td>
                    <td>${order.product_name}</td>
                    <td>${order.quantity}</td>
                    <td>${order.progress}%</td>
                    <td><span class="status-badge status-${statusClass}">${statusText}</span></td>
                    <td>${order.start_date}</td>
                    <td>${order.expected_completion}</td>
                </tr>
            `;
        }).join('');
    }
    
    /**
     * 更新生产图表
     */
    updateProductionCharts(data) {
        if (!data || !window.chartManager) return;
        
        // 更新生产效率图表
        if (data.efficiencyData) {
            window.chartManager.createProductionEfficiencyChart('productionEfficiencyChart', data.efficiencyData);
        }
        
        // 更新产能利用率图表
        if (data.capacityData) {
            window.chartManager.createCapacityChart('capacityChart', data.capacityData);
        }
        
        // 显示生产统计
        const statsContainer = document.querySelector('#production-chart-stats');
        if (statsContainer && data.stats) {
            statsContainer.innerHTML = `
                <div class="chart-stat">
                    <span class="stat-label">日产量:</span>
                    <span class="stat-value">${data.stats.dailyOutput || 0}件</span>
                </div>
                <div class="chart-stat">
                    <span class="stat-label">设备利用率:</span>
                    <span class="stat-value">${data.stats.equipmentUtilization || 0}%</span>
                </div>
                <div class="chart-stat">
                    <span class="stat-label">次品率:</span>
                    <span class="stat-value">${data.stats.defectRate || 0}%</span>
                </div>
            `;
        }
    }
    
    /**
     * 更新配送统计
     */
    updateDeliveryStats(data) {
        if (!data) return;
        
        const statsContainer = document.querySelector('#delivery-stats');
        if (statsContainer) {
            statsContainer.innerHTML = `
                <div class="stat-item">
                    <div class="stat-value">${data.totalShipments || 0}</div>
                    <div class="stat-label">总发货量</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${data.onTimeRate || 0}%</div>
                    <div class="stat-label">准时送达率</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${data.avgDeliveryTime || 0}</div>
                    <div class="stat-label">平均配送时间</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">¥${data.totalCost || 0}</div>
                    <div class="stat-label">配送成本</div>
                </div>
            `;
        }
    }
    
    /**
     * 更新物流状态表格
     */
    updateLogisticsStatus(data) {
        const tbody = document.querySelector('#logisticsTable tbody');
        if (!tbody || !data || !data.shipments) return;
        
        tbody.innerHTML = data.shipments.map(shipment => {
            let statusClass = 'info';
            let statusText = shipment.status;
            
            if (shipment.status === '已送达') statusClass = 'success';
            else if (shipment.status === '配送中') statusClass = 'warning';
            else if (shipment.status === '延误') statusClass = 'danger';
            else if (shipment.status === '待发货') statusClass = 'info';
            
            return `
                <tr onclick="app.showShipmentDetail('${shipment.id}')" style="cursor: pointer;">
                    <td>${shipment.tracking_number}</td>
                    <td>${shipment.order_id}</td>
                    <td>${shipment.destination}</td>
                    <td><span class="status-badge status-${statusClass}">${statusText}</span></td>
                    <td>${shipment.ship_date}</td>
                    <td>${shipment.expected_delivery}</td>
                </tr>
            `;
        }).join('');
    }
    
    /**
     * 更新配送图表
     */
    updateDeliveryCharts(data) {
        if (!data || !window.chartManager) return;
        
        // 更新配送性能图表
        if (data.performanceData) {
            window.chartManager.createDeliveryPerformanceChart('deliveryPerformanceChart', data.performanceData);
        }
        
        // 更新配送成本图表
        if (data.costData) {
            window.chartManager.createDeliveryCostChart('deliveryCostChart', data.costData);
        }
        
        // 显示配送统计
        const statsContainer = document.querySelector('#delivery-chart-stats');
        if (statsContainer && data.stats) {
            statsContainer.innerHTML = `
                <div class="chart-stat">
                    <span class="stat-label">本月发货:</span>
                    <span class="stat-value">${data.stats.monthlyShipments || 0}票</span>
                </div>
                <div class="chart-stat">
                    <span class="stat-label">客户满意度:</span>
                    <span class="stat-value">${data.stats.customerSatisfaction || 0}%</span>
                </div>
                <div class="chart-stat">
                    <span class="stat-label">退货率:</span>
                    <span class="stat-value">${data.stats.returnRate || 0}%</span>
                </div>
            `;
        }
    }
    
    /**
     * 更新质量统计
     */
    updateQualityStats(data) {
        if (!data) return;
        
        const statsContainer = document.querySelector('#quality-stats');
        if (statsContainer) {
            statsContainer.innerHTML = `
                <div class="stat-item">
                    <div class="stat-value">${data.totalInspections || 0}</div>
                    <div class="stat-label">检查次数</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${data.passRate || 0}%</div>
                    <div class="stat-label">合格率</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${data.defectRate || 0}%</div>
                    <div class="stat-label">缺陷率</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${data.customerComplaints || 0}</div>
                    <div class="stat-label">客户投诉</div>
                </div>
            `;
        }
    }
    
    /**
     * 更新检查记录表格
     */
    updateInspectionTable(data) {
        const tbody = document.querySelector('#inspectionTable tbody');
        if (!tbody || !data || !data.inspections) return;
        
        tbody.innerHTML = data.inspections.map(inspection => {
            let statusClass = inspection.result === '合格' ? 'success' : 'danger';
            
            return `
                <tr onclick="app.showInspectionDetail('${inspection.id}')" style="cursor: pointer;">
                    <td>${inspection.batch_number}</td>
                    <td>${inspection.product_name}</td>
                    <td>${inspection.inspector}</td>
                    <td><span class="status-badge status-${statusClass}">${inspection.result}</span></td>
                    <td>${inspection.inspection_date}</td>
                    <td>${inspection.notes || '-'}</td>
                </tr>
            `;
        }).join('');
    }
    
    /**
     * 更新质量图表
     */
    updateQualityCharts(data) {
        if (!data || !window.chartManager) return;
        
        // 更新质量趋势图表
        if (data.trendData) {
            window.chartManager.createQualityTrendChart('qualityTrendChart', data.trendData);
        }
        
        // 更新缺陷分析图表
        if (data.defectData) {
            window.chartManager.createDefectAnalysisChart('defectAnalysisChart', data.defectData);
        }
        
        // 显示质量统计
        const statsContainer = document.querySelector('#quality-chart-stats');
        if (statsContainer && data.stats) {
            statsContainer.innerHTML = `
                <div class="chart-stat">
                    <span class="stat-label">本月检查:</span>
                    <span class="stat-value">${data.stats.monthlyInspections || 0}次</span>
                </div>
                <div class="chart-stat">
                    <span class="stat-label">改进项目:</span>
                    <span class="stat-value">${data.stats.improvementProjects || 0}个</span>
                </div>
                <div class="chart-stat">
                    <span class="stat-label">成本节约:</span>
                    <span class="stat-value">¥${data.stats.costSavings || 0}</span>
                </div>
            `;
        }
    }
    
    /**
     * 显示商品详情
     */
    async showItemDetail(itemId) {
        try {
            const data = await window.apiClient.get(`/inventory/${itemId}`);
            this.showModal('商品详情', this.renderItemDetail(data));
        } catch (error) {
            console.error('获取商品详情失败:', error);
        }
    }
    
    /**
     * 显示订单详情
     */
    async showOrderDetail(orderId) {
        try {
            const data = await window.apiClient.get(`/orders/${orderId}`);
            this.showModal('订单详情', this.renderOrderDetail(data));
        } catch (error) {
            console.error('获取订单详情失败:', error);
        }
    }
    
    /**
     * 渲染商品详情
     */
    renderItemDetail(data) {
        return `
            <div class="detail-content">
                <div class="detail-section">
                    <h4>基本信息</h4>
                    <div class="detail-grid">
                        <div class="detail-item">
                            <label>SKU:</label>
                            <span>${data.sku || '-'}</span>
                        </div>
                        <div class="detail-item">
                            <label>商品名称:</label>
                            <span>${data.name || '-'}</span>
                        </div>
                        <div class="detail-item">
                            <label>类别:</label>
                            <span>${data.category || '-'}</span>
                        </div>
                        <div class="detail-item">
                            <label>单位:</label>
                            <span>${data.unit || '-'}</span>
                        </div>
                    </div>
                </div>
                <div class="detail-section">
                    <h4>库存信息</h4>
                    <div class="detail-grid">
                        <div class="detail-item">
                            <label>当前库存:</label>
                            <span>${data.quantity || 0}</span>
                        </div>
                        <div class="detail-item">
                            <label>安全库存:</label>
                            <span>${data.safetyStock || 0}</span>
                        </div>
                        <div class="detail-item">
                            <label>仓库位置:</label>
                            <span>${data.warehouse || '-'}</span>
                        </div>
                        <div class="detail-item">
                            <label>单价:</label>
                            <span>¥${data.unitPrice || 0}</span>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }
    
    /**
     * 渲染订单详情
     */
    renderOrderDetail(data) {
        return `
            <div class="detail-content">
                <div class="detail-section">
                    <h4>订单信息</h4>
                    <div class="detail-grid">
                        <div class="detail-item">
                            <label>订单号:</label>
                            <span>${data.orderId || '-'}</span>
                        </div>
                        <div class="detail-item">
                            <label>客户:</label>
                            <span>${data.customer || '-'}</span>
                        </div>
                        <div class="detail-item">
                            <label>订单日期:</label>
                            <span>${data.orderDate || '-'}</span>
                        </div>
                        <div class="detail-item">
                            <label>订单金额:</label>
                            <span>¥${data.amount || 0}</span>
                        </div>
                    </div>
                </div>
                <div class="detail-section">
                    <h4>订单状态</h4>
                    <div class="status-info">
                        <span class="status-badge status-${data.status}">${data.statusText || '-'}</span>
                    </div>
                </div>
            </div>
        `;
    }
    
    /**
     * 显示模态框
     */
    showModal(title, content) {
        const modal = document.getElementById('detailModal');
        const modalTitle = document.getElementById('modalTitle');
        const modalBody = document.getElementById('modalBody');
        
        if (modal && modalTitle && modalBody) {
            modalTitle.textContent = title;
            modalBody.innerHTML = content;
            modal.style.display = 'block';
        }
    }
    
    /**
     * 关闭模态框
     */
    closeModal() {
        const modal = document.getElementById('detailModal');
        if (modal) {
            modal.style.display = 'none';
        }
    }
    
    /**
     * 显示错误信息
     */
    showError(message) {
        console.error(message);
        // TODO: 实现更好的错误显示机制
        alert(message);
    }
    
    /**
     * 切换自动刷新
     */
    toggleAutoRefresh(enabled) {
        if (enabled) {
            this.refreshInterval = setInterval(() => {
                this.refreshCurrentModule();
            }, this.refreshIntervalTime);
        } else {
            if (this.refreshInterval) {
                clearInterval(this.refreshInterval);
                this.refreshInterval = null;
            }
        }
    }
    
    /**
     * 刷新当前模块
     */
    async refreshCurrentModule() {
        await this.loadModuleData(this.currentModule);
    }
}

// 计划管理模块初始化
function initPlanningModule() {
    // 初始化子导航标签页切换
    const navItems = document.querySelectorAll('#planning-content .nav-item');
    const tabContents = document.querySelectorAll('#planning-content .tab-content');
    
    navItems.forEach(item => {
        item.addEventListener('click', function() {
            const tabId = this.getAttribute('data-tab');
            
            // 移除所有活动状态
            navItems.forEach(nav => nav.classList.remove('active'));
            tabContents.forEach(tab => tab.classList.remove('active'));
            
            // 添加当前活动状态
            this.classList.add('active');
            document.getElementById(tabId).classList.add('active');
            
            // 初始化对应标签页的图表
            initPlanningCharts(tabId);
        });
    });
    
    // 默认激活第一个标签页
    if (navItems.length > 0) {
        navItems[0].click();
    }
}

// 初始化计划管理图表
function initPlanningCharts(tabId) {
    switch(tabId) {
        case 'demand':
            initDemandChart();
            break;
        case 'capacity':
            initCapacityChart();
            break;
        case 'inventory':
            initInventoryChart();
            break;
        case 'sop':
            initSopChart();
            break;
    }
}

// 需求计划图表
function initDemandChart() {
    const canvas = document.getElementById('demandChart');
    if (!canvas) return;
    
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    canvas.width = canvas.offsetWidth;
    canvas.height = 300;
    
    ctx.fillStyle = '#e8f4fd';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    ctx.fillStyle = '#333';
    ctx.font = '16px Arial';
    ctx.textAlign = 'center';
    ctx.fillText('需求预测图表', canvas.width / 2, canvas.height / 2);
}

// 产能规划图表
function initCapacityChart() {
    const canvas = document.getElementById('capacityChart');
    if (!canvas) return;
    
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    canvas.width = canvas.offsetWidth;
    canvas.height = 300;
    
    ctx.fillStyle = '#fff2e8';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    ctx.fillStyle = '#333';
    ctx.font = '16px Arial';
    ctx.textAlign = 'center';
    ctx.fillText('产能利用率图表', canvas.width / 2, canvas.height / 2);
}

// 库存计划图表
function initInventoryChart() {
    const canvas = document.getElementById('inventoryChart');
    if (!canvas) return;
    
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    canvas.width = canvas.offsetWidth;
    canvas.height = 300;
    
    ctx.fillStyle = '#f0f8e8';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    ctx.fillStyle = '#333';
    ctx.font = '16px Arial';
    ctx.textAlign = 'center';
    ctx.fillText('库存周转率图表', canvas.width / 2, canvas.height / 2);
}

// S&OP执行图表
function initSopChart() {
    const canvas = document.getElementById('sopChart');
    if (!canvas) return;
    
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    canvas.width = canvas.offsetWidth;
    canvas.height = 300;
    
    ctx.fillStyle = '#f0f8ff';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    ctx.fillStyle = '#333';
    ctx.font = '16px Arial';
    ctx.textAlign = 'center';
    ctx.fillText('S&OP执行情况', canvas.width / 2, canvas.height / 2);
}

// 全局函数
window.viewDetails = function(id) {
    console.log('查看详情:', id);
    // TODO: 实现详情查看功能
    alert(`查看详情: ${id}`);
};

window.exportData = function() {
    console.log('导出数据');
    // TODO: 实现数据导出功能
    alert('导出功能开发中...');
};

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
    window.app = new SupplyChainApp();
});

// 页面卸载时清理资源
window.addEventListener('beforeunload', () => {
    if (window.app) {
        // 清理定时器等资源
        console.log('清理应用资源');
    }
});